package com.example.studentvotesystem.controller;

import com.example.studentvotesystem.entity.User;
import com.example.studentvotesystem.service.VoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class VoteController {
    @Autowired
    private VoteService voteService;

    @PostMapping("/vote")
    @ResponseBody
    public Map<String, Object> vote(Integer spotId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            result.put("success", false);
            result.put("msg", "请先登录");
            return result;
        }

        boolean success = voteService.vote(user.getId(), spotId);
        if (success) {
            result.put("success", true);
            result.put("msg", "投票成功");
        } else {
            result.put("success", false);
            result.put("msg", "您已经投过票了");
        }
        return result;
    }
}